const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    totalPages: 0,
    searchKeyword: '',
    productIndex: 0,
    statusIndex: 0,
    productOptions: [{ id: '', name: '全部产品' }],
    statusOptions: ['全部', '启用', '禁用'],
    loading: false
  },

  onLoad() {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/product-models/product-models')) {
      return
    }
    
    this.loadProducts()
    this.loadData()
  },

  onShow() {
    this.loadData()
  },

  onPullDownRefresh() {
    this.setData({
      page: 1
    })
    this.loadData().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom() {
    if (this.data.page < this.data.totalPages) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData(true)
    }
  },

  async loadProducts() {
    try {
      const res = await api.getProductList({
        status: 1
      })

      if (res.code === 1) {
        const products = res.data.list.map(item => ({
          id: item.id,
          name: item.name
        }))
        
        this.setData({
          productOptions: [{ id: '', name: '全部产品' }, ...products]
        })
      }
    } catch (error) {
      console.error('加载产品列表失败:', error)
    }
  },

  async loadData(append = false) {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const params = {
        page: this.data.page,
        limit: this.data.limit
      }

      if (this.data.searchKeyword) {
        params.name = this.data.searchKeyword
      }

      if (this.data.productIndex > 0) {
        params.product_id = this.data.productOptions[this.data.productIndex].id
      }

      if (this.data.statusIndex > 0) {
        params.status = this.data.statusIndex - 1
      }

      const res = await api.getProductModelList(params)

      if (res.code === 1) {
        const list = res.data.list.map(item => ({
          ...item,
          createtime_text: this.formatTime(item.createtime)
        }))

        this.setData({
          list: append ? [...this.data.list, ...list] : list,
          total: res.data.total,
          totalPages: Math.ceil(res.data.total / this.data.limit)
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载型号列表失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  onSearch() {
    this.setData({
      page: 1
    })
    this.loadData()
  },

  onProductChange(e) {
    this.setData({
      productIndex: parseInt(e.detail.value),
      page: 1
    })
    this.loadData()
  },

  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value),
      page: 1
    })
    this.loadData()
  },

  onAdd() {
    if (!this.hasPermission('model_manage', 'add')) {
      wx.showToast({
        title: '您没有新增权限',
        icon: 'none'
      })
      return
    }
    
    wx.navigateTo({
      url: '/pages/product-model-detail/product-model-detail'
    })
  },

  onEdit(e) {
    if (!this.hasPermission('model_manage', 'edit')) {
      wx.showToast({
        title: '您没有编辑权限',
        icon: 'none'
      })
      return
    }
    
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/product-model-detail/product-model-detail?id=${item.id}`
    })
  },

  onDelete(e) {
    if (!this.hasPermission('model_manage', 'delete')) {
      wx.showToast({
        title: '您没有删除权限',
        icon: 'none'
      })
      return
    }
    
    const item = e.currentTarget.dataset.item
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除型号"${item.name}"吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            const result = await api.deleteProductModel(item.id)

            if (result.code === 1) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              this.loadData()
            } else {
              wx.showToast({
                title: result.msg || '删除失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('删除型号失败:', error)
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  onItemClick(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/product-model-detail/product-model-detail?id=${item.id}`
    })
  },

  onPrevPage() {
    if (this.data.page > 1) {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData()
    }
  },

  onNextPage() {
    if (this.data.page < this.data.totalPages) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData()
    }
  },

  formatTime(timestamp) {
    if (!timestamp) return ''
    const date = new Date(timestamp * 1000)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  },

  // 检查是否有权限执行某个操作
  hasPermission(module, action) {
    // 从session中获取管理员信息
    const app = getApp();
    const adminInfo = app.globalData.adminInfo;
    if (!adminInfo || !adminInfo.id) {
      return false;
    }
    
    // 使用权限工具检查权限（基于管理组）
    return permissionUtils.hasPermission(adminInfo.id, module, action);
  }
})
